1 Comparison of R with MATLAB

http://mathesaurus.sourceforge.net/octave-r.html

R (or S-Plus) MATLAB (or Octave) Description
a <- -2.1; b <- 3 a=-2.1; b=3; Assignment; defining a number
a^b\(=-9.261\) a .^ b Power, \(a^b\)
a != b\(=TRUE\) a ~= b Not Equal
!a\(=FALSE\) ~a or not(a) Logical NOT
1i 1i or 1j Imaginary unit
abs(3+4i) or Mod(3+4i)\(=5\) abs(z) Absolute value (modulus)
Re(3+4i)\(=3\) real(z) Real part
Im(3+4i)\(=4\) imag(z) Imaginary part
Arg(3+4i)\(=0.9272952\) arg(z) Argument (radians)
Conj(3+4i)\(=3-4i\) conj(z) Complex conjugate
runif(10) rand(1,10) Uniform distribution
runif(10, min=2, max=7) 2+5*rand(1,10) Uniform: Numbers between 2 and 7
rnorm(10) randn(1,10) Normal distribution
a <- c(2, 3, 4, 5) a=[2, 3, 4, 5]; Row vector, \(1\times n\)-matrix
adash <- t(c(2, 3, 4, 5)) adash=[2, 3, 4, 5]'; Column vector, \(m\times 1\)-matrix
seq(10) or 1:10 1:10 \(1,2,3,\dots,10\)
seq(0, length=10) 0:9 \(0,1,2,\dots,9\)
seq(1,10, by=3) 1:3:10 1, 4, 7, 10
seq(10,1) or 10:1 10:-1:1 \(10,9,8,\dots,1\)
seq(from=10, to=1, by=-3) 10:-3:1 10, 7, 4, 1
seq(1,10, length=7) linspace(1,10,7) Linearly-spaced vector of \(n=7\) points: 1, 2.5, 4, 5.5, 7, 8.5, 10
c(a,a)\(=2, 3, 4, 5, 2, 3, 4, 5\) [a a] Concatenate two vectors, end-to-end
c(1:4,a) \(=1, 2, 3, 4, 2, 3, 4, 5\) [1:4 a]
rep(a, times=2) [a a] \(2, 3, 4, 5, 2, 3, 4, 5\)
rep(a, each=3) \(2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5\)
rep(a,a) \(2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5\)
a[-1] \(=3, 4, 5\) a(2:end) miss the first element
a[-10] a([1:9]) miss the tenth-element (of ten)
a[-seq(1,50,3)] \(=3, 4\) miss \(1,4,7,\dots\)
a[length(a)] \(=5\) a(end) last element
a[(length(a)-1):length(a)] \(=4, 5\) a(end-1:end) last two elements
pmax(a,b) max(a,b) pair-wise max
max(c(a,b)) max([a b]) max of all values in two vectors
v <- max(a) \(=5\) ; i <- which.max(a) \(=4\) [v,i] = max(a)
a*a \(=4, 9, 16, 25\) a.*a Multiply two vectors (element-wise) \(a^2\)
u %*% v dot(u,v) Vector dot-product, \(u\bullet v\)
rbind(c(2,3), c(4,5)) or array(c(2,3,4,5), dim=c(2,2) ) a = [2 3; 4 5] Define a matrix
rbind(a,b) [a ; b] Bind rows
ab <- cbind(a,b) [a , b] Bind columns
rbind(1:4, 1:4) [1:4 ; 1:4] Bind rows (from two vectors)
cbind(1:4,1:4) [1:4 ; 1:4]' Bind columns (from two vectors)
matrix(data=0,nrow=3,ncol=5) or array(0,c(3,5)) zeros(3,5) \(0\)-filled array
matrix(1,3,5) or array(1,c(3,5)) ones(3,5) \(1\)-filled array
as.vector(t(a)) \(=2, 3, 4, 5\) a'(:) Flatten to vector (by rows, like comics)
as.vector(a) a(:) Flatten to vector (by columns)
a <- rbind( c(11, 12, 13, 14), c(21, 22, 23, 24), c(31, 32, 33, 34) ) a= [ 11 12 13 14 ; 21 22 23 24 ; 31 32 33 34 ] Input is a \(3\times4\) array
a[2,3] \(=23\) a(2,3) Single-Element \(2,3\) (row=2,col=3)
a[1,] \(=11, 12, 13, 14\) a(1,:) First row
a[,1] \(=11, 21, 31\) a(:,1) First column
a[-1,] \(=21, 31, 22, 32, 23, 33, 24, 34\) a(2:end,:) All, except first row
a[(nrow(a)-1):nrow(a),] \(=21, 31, 22, 32, 23, 33, 24, 34\) a(end-1:end,:) Last two rows
a[(ncol(a)-1):ncol(a),] \(=13, 23, 33, 14, 24, 34\) a(:,end-1:end) Last two columns
a[,seq(1,ncol(a),by=2)] \(=11, 21, 31, 13, 23, 33\) a(:,1:2:end) Strides: Every other column
a[-2,-3] \(=11, 31, 12, 32, 14, 34\) All, except 2nd-row, and 3rd-column
a[,-2] \(=11, 21, 31, 13, 23, 33, 14, 24, 34\) a(:,[1 3 4]) Remove 2nd column
a[,1] <- 99 a(:,1) = 99
a[,1] <- c(99,98,97) a(:,1) = [99 98 97]'
a[a>90] <- 90 a(a>90) = 90; Clipping: Replace all elements over 90
t(a) a' Transpose
a=matrix( c(3,4,2, 2,8,6, 1,4,7), nrow=3, byrow=TRUE) a=[3, 4, 2 ; 2, 8, 6 ; 1, 4, 7] (example data for sorting)
t(sort(a)) \(=1, 2, 2, 3, 4, 4, 6, 7, 8\) sort(a(:)) Flattened and sorted
apply(a,2,sort) \(=1, 2, 3, 4, 4, 8, 2, 6, 7\) sort(a) Sort each column
t( apply(a,1,sort) ) \(=2, 2, 1, 3, 6, 4, 4, 8, 7\) sort(a')' Sort each row
sortrows(a,1) Sort rows (by first row)
order(a)\(=3, 2, 7, 1, 4, 6, 8, 9, 5\) Sort, return indices
apply(a,2,max) \(=3, 8, 7\) max(a) max in each column
apply(a,1,max) \(=4, 8, 7\) max(a') max in each row
max(a) \(=8\) max(max(a)) overall max throughout entire array
i <- apply(a,1, which.max) \(=2, 2, 3\) [v i] = max(a) return row-indices, i, of which row holds the max value of that column
pmax(b,c) max(b,c) pair-wise max
apply(a,2, cummax) \(=3, 3, 3, 4, 8, 8, 2, 6, 7\) cummax(a) cumulative max
a[,3:1] \(=2, 6, 7, 4, 8, 4, 3, 2, 1\) fliplr(a) Flip left-right
a[3:1,] \(=1, 2, 3, 4, 8, 4, 7, 6, 2\) flipud(a) Flip up-down
dim(a) \(=3, 3\) size(a) Matrix dimensions
ncol(a) \(=3\) size(a,2) or length(a) Number of columns
prod(dim(a)) \(=9\) length(a(:)) Number of elements
ndims(a) Number of dimensions
a * b a .* b Element-wise operations
a %*% b a * b Matrix product (or vector dot-product)
outer(a,b) or a %o% b Outer product
which(a != 2) \(=1, 3, 4, 5, 6, 8, 9\) find(a) Not-equal-to-2 elements, indices
which(a != 2, arr.ind=TRUE) \(=1, 3, 1, 2, 3, 2, 3, 1, 1, 2, 2, 2, 3, 3\) [i j] = find(a) Not-equal-to-2 elements, array indices
ij <- which(a != 2, arr.ind=TRUE); v <- a[ij] [i j v] = find(a) Vector of not-equal-to-2 values
which(a>5.5) \(=5, 8, 9\) find(a>5.5) Condition, indices
ij <- which(a>5.5, arr.ind=TRUE); v <- a[ij] \(=8, 6, 7\) Return the values
a .* (a>5.5) Only keep those elements above \(5.5\), else zeroize
a= cat(3, [1 2; 1 2], [3 4; 3 4]); Define a 3-way array
a(1,:,:)
f <- read.table( "data.txt") f = load('data.txt') Reading from a file (2d)
plot(a, type="l") plot(a) 1-dimensional (line) plot
plot(x[,1],x[,2]) plot(x(:,1),x(:,2),'o') 2-dimensional scatter-plot
plot(x1,y1); lines(x2,y2) plot(x1,y1); hold on; plot(x2,y2) Overplotting: Add new plots onto current
par(mfrow=c(2,1)) subplot(211) subplots
plot(x,y, type="b", col="red") plot(x,y,'ro-') Plotting symbols and color
plot(c(1:10,10:1), asp=1) axis equal 1:1 aspect-ratio
plot(x,y, xlim=c(0,10), ylim=c(0,5)) axis([ 0 10 0 5 ]) Set axes-limits manually
plot(1:10, main= "title", xlab= "x-axis", ylab= "y-axis") title('title'); xlabel('x-axis'); ylabel('y-axis') Axis labels and titles
grid() grid on Turn on grid lines
plot(x,y, log="y") semilogy(a) logarithmic y-axis
plot(x,y, log="x") semilogx(a) logarithmic x-axis
plot(x,y, log="xy") loglog(a) logarithmic x and y axes
f <- function(x) sin(x/3) - cos(x/5) f= inline( 'sin(x/3) - cos(x/5)') Defining functions
plot(f, xlim=c(0,40), type='p') ezplot(f,[0,40]); fplot( 'sin(x/3) - cos(x/5)', [0,40]) Plot a function for given range
theta= 0:0.001:2*pi; r= sin(2*theta);
polar(theta, rho)
hist(rnorm(1000)) hist(randn(1000,1))
hist(rnorm(1000), breaks= -4:4) hist(randn(1000,1), -4:4)
hist(rnorm(1000), breaks=c(seq(-5,0,0.25), seq(0.5,5,0.5)), freq=FALSE)
plot( apply(a,1,sort), type="l") plot(sort(a))
contour(z) contour(z) Contour plot
filled.contour(x,y,z, nlevels=7, color= gray.colors) contourf(z); colormap(gray) Filled contour plot
image(z, col= gray.colors(256)) image(z); colormap(gray) Plot image data
quiver() Direction-field vectors
f <- function(x,y) x*exp(-x^2-y^2); n <- seq(-2,2, length=40); z <- outer(n,n,f) n=-2:.1:2; [x,y]= meshgrid(n,n); z=x.*exp(-x.^2-y.^2);
persp(x,y,z, theta=30, phi=30, expand=0.6, ticktype= 'detailed') mesh(z) Mesh plot
persp(x,y,z, theta=30, phi=30, expand=0.6, col= 'lightblue', shade=0.75, ltheta=120, ticktype= 'detailed') surf(x,y,z) or surfl(x,y,z) Surface plot
lattice::cloud(z~x*y) plot3(x,y,z,'k+') 3d scatter plot
postscript( file= "foo.eps"); plot(1:10); dev.off() plot(1:10); print -depsc2 foo.eps PostScript
pdf(file= 'foo.pdf') PDF
svg(file= 'foo.svg') SVG (vector graphics for www)
png(filename= "Rplot.png") print -dpng foo.png PNG (raster-graphics)
a <- c(1, 2, 2, 5, 2); b <- c(2, 3, 4) a= [ 1, 2, 2, 5, 2 ]; b= [ 2, 3, 4 ]; Create sets
unique(a) \(=1, 2, 5\) unique(a) Set unique
union(a,b) \(=1, 2, 5, 3, 4\) union(a,b) Set union
intersect(a,b) \(=2\) intersect(a,b) Set intersection
setdiff(a,b) \(=1, 5\) setdiff(a,b) Set difference
setdiff( union(a,b), intersect(a,b) ) \(=1, 5, 3, 4\) setxor(a,b) Set exclusion
a=matrix( c(3,4,2, 2,8,6, 1,4,7), nrow=3, byrow=TRUE) a=[3, 4, 2 ; 2, 8, 6 ; 1, 4, 7] (example data for following)
is.element(2,a) or 2 %in% a \(=TRUE\) ismember(2,a) True for set-membership
apply(a,2, mean) \(=2, 5.3333333, 5\) mean(a) Average (column-wise)
apply(a,2, median) \(=2, 4, 6\) median(a) Median (column-wise)
apply(a,2, sd) \(=1, 2.3094011, 2.6457513\) std(a) Standard deviation (column-wise)
apply(a,2, var) \(=1, 5.3333333, 7\) var(a) Variance (column-wise)
z <- lm(y~x); plot(x,y); abline(z) z= polyval( polyfit(x,y,1), x); plot(x,y, 'o', x,z ,'-') Straight-line fit
polyroot(c(1,-1,-1)) roots([1 -1 -1]) Find zeros of polynomial
fft(a) fft(a) Fast fourier transform
fft(a, inverse=TRUE) ifft(a) Inverse fourier transform
# comment here % comment here Comment-symbol (ignore rest-of-line)
library(graphics) % must be in MATLABPATH Import library functions
print(a) disp(a) Print
for(i in 1:5) print(i) for i=1:5; disp(i); end for-statement
for(i in 1:5) {print(i); print(i*2)} for i=1:5, disp(i); disp(i*2); end Multi-line for statements
if (1>0) a <- 100 if 1>0 a=100; end if-statement
if (1>0) a <- 100 else a <- 0 if 1>0 a=100; else a=0; end if-else statement

R (or S-Plus) MATLAB (or Octave) Description
help.start() doc Browse help interactively
help() help help or doc doc Help on using help
help(plot) or ?plot help plot Help for a function
help(package= 'splines') help splines or doc splines Help for a toolbox/ library package
demo() demo Demonstration examples
example(plot) Example using a function
help.search('plot') lookfor plot Search help files
apropos('plot') Find objects by partial name
library() help List available packages
find("plot") which plot Locate functions
methods(plot) List available methods for a function
source('foo.R') foo (or foo.m) Run code from file
history() history Command history
savehistory( file= ".Rhistory") diary on [… some more code …] diary off Save command history
q(save= 'no') exit or quit End session
help(Syntax) help - Help on operator syntax
a %% b \(=1, 2, 1, 0, 2, 0, 0, 0, 3\) rem(a,b) Remainder
a %/% b \(=1, 0, 0, 2, 2, 1, 1, 2, 1\) Integer division
factorial(b+1)\(=6, 24, 120\) factorial(b+1) Factorial, \(n!\)
a & b \(=T, T, T, T, T, T, T, T, T\) a & b or and(a,b) Element-wise logical AND of two vectors/ matrices
a | b \(=T, T, T, T, T, T, T, T, T\) a | b or or(a,b) Element-wise logical OR of two vectors/ matrices
a && b \(=TRUE\) a && b Logical AND of two logical-values (short-circuiting)
a || b \(=TRUE\) a || b Logical OR of two logical-values (short-circuiting)
any(a) \(=TRUE\) any(a) True if some/any of the elements are non-zero
all(a)\(=TRUE\) all(a) True if all of the elements are non-zero
round(a)\(=3, 2, 1, 4, 8, 4, 2, 6, 7\) round(a) Round (for R: IEC60559 = nearest even)
ceiling(a)\(=3, 2, 1, 4, 8, 4, 2, 6, 7\) ceil(a) Round up
floor(a)\(=3, 2, 1, 4, 8, 4, 2, 6, 7\) floor(a) Round down
as.integer(a) fix(a) Round towards zero
z <- 3+4i z= 3+4i A complex number, \(3+4\imath\)
atan2(b,a) atan(a,b) Arctangent, \(\arctan(\frac{b}{a})\)
matrix(runif(36),6) rand(6) Uniform \(6\times 6\) array
rev(a)\(=7, 6, 2, 4, 8, 4, 1, 2, 3\) reverse(a) Reverse
a[] <- 3 a(:)= 3 Set all values to same scalar-value
matrix(9,3,5) or array(9,c(3,5)) ones(3,5)*9 Any number-filled array
diag(1,3) eye(3) Identity matrix
diag(c(4,5,6)) diag([4 5 6]) Diagonal
magic(3) Magic squares; Lo Shu
a <- matrix(1:6, nrow=3, byrow=TRUE) reshape(1:6,3,2)'; Reshaping (rows first)
matrix(1:6, nrow=2) or array(1:6,c(2,3)) reshape(1:6,2,3); Reshaping (columns first)
a[row(a) <= col(a)] vech(a) Flatten upper triangle (by columns)
a([1 3],[1 4]); Array as indices
a.' or transpose(a) Non-conjugate transpose
det(a) det(a) Determinant
solve(a) inv(a) Inverse
pracma::pinv or MASS::ginv pinv(a) Pseudo-inverse
norm(a) Norms
eigen(a )$values eig(a) Eigenvalues
eigen( rbind(a, a[,1]) )$values eig(a) Eigenvalues
svd(a)$d svd(a) Singular values
chol(a) Cholesky factorization
eigen(a)$vectors [v,l] = eig(a) Eigenvectors
eigen( rbind(a, a[,1]) )$vectors [v,l] = eig(a) Eigenvectors
rank(a) rank(a) Rank
apply(a,2,sum) sum(a) Sum of each column
apply(a,1,sum) sum(a') Sum of each row
sum(a) sum(sum(a)) Sum of all elements
apply(a,2, cumsum) cumsum(a) Cumulative sum (columns)
rot90(a) Rotate 90 degrees
kronecker( matrix(1,2,3), a) repmat(a,2,3) Repeat matrix: \(\left[\begin{matrix} a & a & a \cr a & a & a\end{matrix} \right]\)
a[lower.tri(a)] <- 0 triu(a) Triangular, upper
a[upper.tri(a)] <- 0 tril(a) Triangular, lower
[a(:), b(:)] Concatenate multi-dimensional matrices into one long vector
object.size(a) \(=328\) Number of bytes used in memory
crossprod(a,b) or t(a) %*% b Cross product
kronecker(a,b) kron(a,b) Kronecker product
a / b Matrix division, \(b{\cdot}a^{-1}\)
solve(a,b) a \ b Left matrix division, \(b^{-1}\cdot a\) (solve linear equations)
f <- read.table( file= "data.csv", sep=";") x = dlmread( 'data.csv', ';') Reading fram a CSV file (2d)
write( f, file="data.txt") save -ascii data.txt f Writing to a file (2d)
plot(t,s, type="n", xlab="", ylab=""); polygon(t,s, col= "lightblue"); polygon(t,c, col= "lightgreen") fill(t,s,'b', t,c,'g') % fill has a bug? Filled plot
stem(x[,3]) Stem-and-Leaf plot
plot(x1,y1, x2,y2) Two graphs in one plot
.Last.value ans Most recent evaluated expression
objects() whos or who List variables loaded into memory
rm(x) clear x or clear all Clear variable \(x\) from memory
ifelse(a>0,a,0) Ternary operator (if?True:False)
list.files() or dir() dir or ls List files in directory
list.files( pattern=".r") what List script files in directory
getwd() pwd Displays the current working directory
setwd('foo') cd foo Change working directory
system("notepad") !notepad Invoke a System Command
cor(x,y) corr(x,y) Correlation coefficient
cov(x,y) cov(x,y) Covariance
solve(a,b) a= x\y Linear least-squares \(y=ax+b\)
polyfit(x,y,3) Polynomial fit
f= inline( '1/x - (x-1)'); fzero(f,1) Find a zero near \(x=1\)
(see packages Ryacas, rSymPy) solve('1/x = x-1') Solve symbolic-equations
polyval([1 2 1 2], 1:10) Evaluate polynomial
diff(a) Discrete difference function and approximate derivative
factor() Factorization
.R .m Script file extension
string <- "a <- 234"; eval(parse(text=string)) string='a=234'; eval(string) Eval

Time-stamp: “2007-11-09T16:46:36 vidar” ©2006 Vidar Bronken Gundersen, /mathesaurus.sf.net


1.2 CRAN Task Views

Over 30 CRAN task-views allow one to browse the many packages by specialized topic:

Task-view Description
Bayesian Bayesian Inference
ChemPhys Chemometrics and Computational Physics
ClinicalTrials Clinical Trial Design, Monitoring, and Analysis
Cluster Cluster Analysis & Finite Mixture Models
DifferentialEquations Differential Equations
Distributions Probability Distributions
Econometrics Econometrics
Environmetrics Analysis of Ecological and Environmental Data
ExperimentalDesign Design of Experiments (DoE) & Analysis of Experimental Data
ExtremeValue Extreme Value Analysis
Finance Empirical Finance
Genetics Statistical Genetics
Graphics Graphic Displays & Dynamic Graphics & Graphic Devices & Visualization
HighPerformanceComputing High-Performance and Parallel Computing with R
MachineLearning Machine Learning & Statistical Learning
MedicalImaging Medical Image Analysis
MetaAnalysis Meta-Analysis
Multivariate Multivariate Statistics
NaturalLanguageProcessing Natural Language Processing
NumericalMathematics Numerical Mathematics
OfficialStatistics Official Statistics & Survey Methodology
Optimization Optimization and Mathematical Programming
Pharmacokinetics Analysis of Pharmacokinetic Data
Phylogenetics Phylogenetics, Especially Comparative Methods
Psychometrics Psychometric Models and Methods
ReproducibleResearch Reproducible Research
Robust Robust Statistical Methods
SocialSciences Statistics for the Social Sciences
Spatial Analysis of Spatial Data
SpatioTemporal Handling and Analyzing Spatio-Temporal Data
Survival Survival Analysis
TimeSeries Time Series Analysis
WebTechnologies Web Technologies and Services
gR gRaphical Models in R
  • For developing DSP demos (e.g. with processing using FFTs, DCTs, wavelets, sound, images, symbolic math), in addition to the packages used within this PeZdemoR demo, some other R-packages that would be useful include:
    • fftwtools, fftw, wavethresh, wmtsa, waveslim, wavelets, waved, dtt, seewave, monitoR, phontools, warbleR, ripa, imager, EBImage, magick, Ryacas, rSymPy, … more

  • This current presentation itself was produced within RStudio [@RStudio1], using
    • knitr engine [@Yihui2016]
    • pandoc utility [@website:pandoc1]
    • convert from RMarkdown [@pkgrmarkdown] format
    • into this Slidy presentation.


1.3 The shiny Package

  • (free) contributed package to R that makes it incredibly easy to deliver interactive data summaries and queries to end users, through any web-browser
  • comes with a variety of widgets for quickly building user-interfaces
  • default styling of any shiny-generated application is based upon the default Bootstrap theme
    • extensible, and it is easy to integrate a shiny-application with any web content, using HTML, CSS, and JavaScript libraries, like jQuery.js (and many others)

Copyright © 2017 DiYZerProductionMine, Inc. All rights reserved. Webmaster